import requests
from bs4 import BeautifulSoup
import csv

year = 2003
ret = []
while year < 2023:
    url='https://view.lottery.sina.com.cn/lotto/pc_zst/index?lottoType=ssq&actionType=chzs&year=%s&dpc=1' % (str(year))
    resp=requests.get(url)
    resp.encoding='utf-8'
    soup=BeautifulSoup(resp.text,"lxml")

    red_start = 5
    red_end = 39 + 1

    i = 1
    while True:
        b = '#cpdata > tr:nth-child(%s)' % (str(i))
        data = soup.select(b)
        if len(data) == 0:
            break
        red_data = data[0].find_all('td')[red_start-1:red_end-1]
        temp = []
        for j in red_data:
            if j['class'][0][:9] == "chartball":
                temp.append(j.text)
        ret.append(temp)
        i += 1
    
    year += 1


with open('data.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    for row in ret:
        writer.writerow(row)